import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLoginOut } from "@/api";
import { setToken, getToken, removeToken } from '@/utils/token'
const state = {
  code: '',
  token: getToken(),
  userInfo: {}
}

//mutations 修改state的唯一手段  state.categoryList是上方state里的空数组，后面的赋值是从actions里收到的参数result.data
const mutations = {
  GETCODE(state, code) {
    state.code = code
  },
  USERLOGIN(state, token) {
    state.token = token
  },
  GETUSERINFO(state, userInfo) {
    state.userInfo = userInfo
  },
  CLEARUSERINFO(state) {
    state.token = '',
      state.userInfo = {},
      removeToken()
  }

}

//actions 可以书写的业务
const actions = {
  async getCode({ commit }, phone) {
    let result = await reqGetCode(phone)
    if (result.code == 200) {
      commit('GETCODE', result.data)
      return '成功'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  async userRegister({ commit }, user) {
    let result = await reqUserRegister(user)
    if (result.code == 200) {
      return '成功'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  async userLogin({ commit }, data) {
    let result = await reqUserLogin(data)
    if (result.code == 200) {
      commit('USERLOGIN', result.data.token)
      setToken(result.data.token)
      return '成功'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  async getUserInfo({ commit }) {
    let result = await reqUserInfo()
    if (result.code == 200) {
      commit("GETUSERINFO", result.data)
      return '成功'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  async getUserLogOut({ commit }) {
    let result = await reqLoginOut()
    if (result.code == 200) {
      commit('CLEARUSERINFO')
      return '成功'
    } else {
      return Promise.reject(new Error('faile'))
    }
  }
}


//理解为计算属性用于简化仓库数 ，让组件读取数据更快
const getters = {

}
export default {
  state,
  mutations,
  actions,
  getters
}